package com.hy.dao;

import com.hy.bean.Follow;
import com.hy.utils.DBManager;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class FollowDao {
    private QueryRunner qr = new QueryRunner();

    public long selectgz(Integer id) throws Exception {
        Connection conn = DBManager.getConn();

        String sql = "select count(*) from follow where user_id = ? and tombstone = '0'";

        long count = qr.query(conn, sql, new ScalarHandler<Long>(), id);

        DbUtils.close(conn);
        return count;
    }

    public List<Map<String, Object>> selectBy(int user_id) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "select * FROM ums_user inner JOIN follow on  user_id = id where user_id = ?";
        MapListHandler mlh = new MapListHandler();
        List<Map<String, Object>> mapList = qr.query(conn, sql, mlh, user_id);

        DbUtils.close(conn);
        return mapList;
    }

    public long selectBy(Integer id,Integer uId) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "select count(*) from follow where user_id = ? and user1_id=?";
        long count = qr.query(conn, sql, new ScalarHandler<Long>(), id, uId);
        DbUtils.close(conn);
        return count;
    }

    public boolean insert(Follow follow) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "insert into follow values (?,?,?,null,?,null,?)";
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        int count = qr.update(conn, sql,follow.getUser_id(),follow.getUser1_id(),formatter.format(date),follow.getCreate_id(),follow.getTombstone());
//        DbUtils.close(conn);  n,  m
        return count>0?true:false;
    }

    public boolean update(Follow follow) throws Exception {
        Connection conn = DBManager.getConn();
        String sql = "update follow set tombstone = ?,update_time=?,update_id=? where user_id=? and user1_id=?";
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        int count = qr.update(conn, sql,follow.getTombstone(),formatter.format(date),follow.getUpdare_id(),follow.getUser_id(),follow.getUser1_id());
        DbUtils.close(conn);
        return count>0?true:false;
    }

    public static void main(String[] args) throws Exception {
        FollowDao m = new FollowDao();

        System.out.println(m.insert(new Follow(1, 3, null, null,1, null, "0")));
    }
}
